<template>
	<view class="full-page">
		<cu-custom bgColor="bg-gradual-blue" iconClass='text-white'>
			<block slot="content" style='color: white;'>个人中心
			</block>
		</cu-custom>
		<view class="bg-gradual-blue flex-row justify-start align-center" style="padding: 15px;">

			<image v-if="userInfo" :src="userInfo.head_url" mode="aspectFit" class="cu-avatar round"
				style="width: 75px;height: 75px" @click="to_page('./edit')">
			</image>

			<view class="padding-sm"></view>

			<view class="flex-column align-start" v-if="userInfo">
				<!-- <input type="nickname" v-model="userInfo.nickName" class="weui-input" :value="nickName" @blur="bindblur"
					placeholder="请输入昵称" @input="bindinput" /> -->

				<view v-if="!editName">{{userInfo.nick_name}} <text @click="editName=true"
						style="text-decoration: underline;margin-left: 12px;font-size: 12px;">修改></text></view>
				<view style="display: flex;flex-direction: row;justify-content: space-around;align-items: center;"
					v-if="editName"><input type="nickname" class="weui-input"
						style="border:1px solid #F2F2F2;background-color: white;color:black;"
						:value="userInfo.nick_name" @blur="bindblur" placeholder="请输入昵称" @input="bindinput" /><text
						style="text-decoration: underline;margin-left: 12px;font-size: 12px;"
						@click="setNickname()">确认</text></view>
				<view v-if="userInfo.role=='admin'" class="text-bold margin-top-xs">角色：管理员</view>
				<view v-if="userInfo.role=='acceptor'" class=" margin-top-xs">角色：受理员</view>
				<view class="padding-xs"></view>

			</view>
		</view>

		<view class="flex-row justify-center" v-if="userInfo">
			<button class='cu-btn bg-white shadow' style="margin-top: 25px;width: 96%;height: 35px;"
				@click="removeToken">退出登录</button>
		</view>

		<view class="flex-row justify-center" v-else>
			<button class='cu-btn bg-white shadow' style="margin-top: 25px;width: 96%;height: 35px;"
				@click="wxGetUserInfo()">授权登录</button>
		</view>


		<view class="safe-area botton-nav">
			<view @click="toHome()" style="width: 50%;height:38px;line-height: 38px;background-color:#F2F2F2;"> <text
					class="cuIcon-homefill margin-right-xs"></text>首页</view>
			<view style="width: 50%;height:38px;line-height: 38px;" class="bg-gradual-blue text-white text-bold"><text
					class="cuIcon-myfill margin-right-xs"></text>我的</view>
		</view>

		<uni-popup ref="popup" type="center">
			<view class="loginView">
				<view class="loginTitle" style="">授权获取个人信息</view>
				<image src="../../static/wxProgram.png"></image>
				<view>申请获取您微信的头像、昵称！</view>
				<button class='cu-btn bg-green shadow' @click="wxGetUserInfo()">授权登录</button>
			</view>
		</uni-popup>
		<view class="cu-modal" :class="modalName=='phoneModal'?'show':''">
			<view class="cu-dialog" style="width: 300px;">
				<view class="loginView">
					<view class="loginTitle" style="">授权获取手机号</view>
					<image src="../../static/wxProgram.png"></image>
					<view>授权获取手机号！</view>
					<button class='cu-btn phone bg-green' open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber">授权手机号</button>
				</view>
			</view>
		</view>

	</view>
</template>

<script>
	import uniPopup from "@/components/uni-popup/uni-popup.vue";
	const defaultAvatarUrl =
		'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

	export default {
		components: {
			uniPopup,
		},
		data() {
			return {
				modalName: '',
				editName: false,
				nickname: "",
				userInfo: null,
				head_url: defaultAvatarUrl,
				isLogin: uni.getStorageSync('isLogin') || false,
			};
		},
		methods: {
			toHome() {
				uni.redirectTo({
					url: '/pages/index/index'
				})
			},
			to_page() {
				uni.reLaunch({
					url: '/pages/index/index'
				})
			},
			bindblur(e) {
				this.userInfo.nick_name = e.detail.value; // 获取微信昵称
			},
			bindinput(e) {
				this.userInfo.nick_name = e.detail.value; //这里要注意如果只用blur方法的话用户在输入玩昵称后直接点击保存按钮，会出现修改不成功的情况。
			},
			setNickname() {
				this.editUserName();
				uni.setStorageSync('userInfo', this.userInfo)
				this.editName = false;
			},
			editUserName() {
				let _this = this;
				uni.showLoading()
				let para = {
					nick_name: this.userInfo.nick_name
				}
				_this.$http.put('app/app_user/' + this.userInfo.id, para, (res) => {
					uni.hideLoading()
					if (res.data.code == 20000) {
						uni.showToast({
							title: '提交成功'
						})
					}
				});
			},
			checkToken() {
				let _this = this;
				if (!_this.isLogin) {} else {
					_this.getInfo()
				}
			},
			removeToken() {
				this.userInfo = null
				this.isLogin = false
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('token')
				uni.removeStorageSync('isLogin')
				this.to_page('../index/index')
			},
			// 获取个人信息
			wxGetUserInfo() {
				var _this = this;
				uni.showModal({
					title: '温馨提示',
					content: '亲，授权微信登录后才能正常使用小程序功能',
					success(res) {
						//如果用户点击了确定按钮
						if (res.confirm) {
							_this.login()
						} else if (res.cancel) {
							//如果用户点击了取消按钮
							uni.showToast({
								title: '您拒绝了请求,不能正常使用小程序',
								icon: 'error',
								duration: 2000
							});
							return;
						}
					}
				})

			},
			login() {
				let _this = this;
				// 1.wx获取登录用户code
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						let code = loginRes.code;
						//2.将用户登录code传递到后台置换用户SessionKey、OpenId等信息
						_this.getUserToken(code);
					},
				});
			},
			getUserToken(code) {
				let _this = this;
				console.log('开始向服务器获取登录信息！');
				_this.$http.get('app/app_user/login', {
					data: {
						code: code,
					}
				}, (res) => {
					if (res.data.code == 20000) {
						uni.setStorageSync('token', res.data.token);
						uni.setStorageSync('userInfo', res.data.item);
						_this.userInfo = res.data.item;
						_this.$refs.popup.close() //隐藏弹窗
						_this.isLogin = true
						uni.setStorageSync('isLogin', _this.isLogin);
						console.log(_this.userInfo)
						// 如果用户角色为管理员，提示订阅消息
						if (_this.userInfo.role === 'admin') {
							_this.subscribeConfirm()
						}
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'fail'
						})
					}
				});
			},
			getInfo() {
				var _this = this;
				var para = {}
				_this.$http.get('app/app_user', {
					data: para
				}, (res) => {
					if (res.data.code == 20000) {
						let info = res.data.info
						uni.setStorageSync('userInfo', info);
						_this.userInfo = info
						if (info.role == 'admin' && info.subscribe_on) {
							_this.subscribeConfirm()
						}
					} else if (res.data.code == 40001 || res.statusCode == 401) {
						_this.wxGetUserInfo()
					} else {
						uni.showToast({
							title: res.data.msg,
							icon: 'fail'
						})
					}
				});
			},
			subscribeConfirm() {
				let _this = this
				let toast_icon = '';
				let toast_content = ''
				wx.showModal({
					title: '订阅消息提示',
					content: '您是管理员，开启工单订阅消息？',
					showCancel: false,
					confirmText: '开启',
					success(res) {
						if (res.confirm) {
							// 用户点击确定，调用订阅消息接口
							uni.requestSubscribeMessage({
								tmplIds: ['S4NIsxVKQwnORaYGkVbWf2a7AKeMP0zDZa_IguZqRQg'],
								success(res) {
									if (res['S4NIsxVKQwnORaYGkVbWf2a7AKeMP0zDZa_IguZqRQg'] === 'accept') {
										// 用户同意订阅消息
										wx.showModal({
											title: '订阅成功',
											// content: '订阅成功',
											showCancel: false,
											confirmText: '确认',
											success(res) {}
										})
										_this.editSubscribeOn()
										console.log('订阅工单消息成功', res);
									} else {
										// 用户拒绝订阅消息
										wx.showModal({
											title: '订阅消息提示',
											content: '您拒绝了订阅，将收不到订阅工单消息',
											// showCancel: false,
											confirmText: '重新订阅',
											cancelText: '确认拒绝',
											success(res) {
												if (res.confirm) {
													_this.subscribeConfirm()
												}
												console.log(res)
											}
										})
									}
								},
								fail(err) {
									// 请求订阅消息失败
									wx.showModal({
										title: '订阅消息提示',
										content: '订阅失败',
										// showCancel: false,
										confirmText: '重新订阅',
										cancelText: '取消订阅',
										success(res) {
											if (res.confirm) {
												_this.subscribeConfirm()
											}
											console.log(res)
										}
									})
									console.error('请求订阅消息失败', err);
								},
							});

						}
					}
				})
			},
			editSubscribeOn() {
				let _this = this;
				let para = {
					subscribe_on: 0
				}
				_this.$http.put('app/app_user/' + this.userInfo.id, para, (res) => {
					if (res.data.code == 20000) {
						console.log('订阅弹窗关闭成功')
					}
				});
			},
		},
		onLoad() {},
		mounted() {
			this.checkToken()
			this.userInfo = uni.getStorageSync('userInfo');
			console.log(this.head_url)
		},
		onShareAppMessage: function() {

		}
	}
</script>

<style lang="scss">
	.botton-nav {
		position: fixed;
		bottom: 0;
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		align-items: center;
		width: 100vw;
		text-align: center;
	}

	.safe-area {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	.box {
		margin: 0 0 0 0;
		position: fixed;
		bottom: 0px;
		width: 100vw;

		.safe-area {
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
		}
	}

	.flex-row {
		align-items: center;
	}

	.login-form {
		width: 96%;
		margin-top: 25px;
		margin-left: 2%;
		padding: 0 12px;
		background-color: #fff;
		box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
		border-radius: 7px;
	}

	.icon-style {
		font-size: 22px;
		color: rgb(72, 157, 238);
		;
	}

	.cu-input {
		height: 40px;
		width: 80%;
		padding: 10px;
		border: 1px solid #ddd;
		border-radius: 7px;
	}

	.forget-password {
		color: #999;
		font-size: 12px;
	}

	.register {
		text-align: center;
		color: #999;
		font-size: 12px;
	}

	.register-btn {
		color: #f00;
		cursor: pointer;
	}

	.mybar {
		width: 100%;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid rgb(203, 203, 203);
		height: 50px;
	}
</style>